package com.hy.frame.mvvm.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding


abstract class BaseFragment<DB : ViewDataBinding, VM : BaseViewModel> : com.hy.frame.base.BaseFragment() {
    protected var mBinding: DB? = null
    protected var mModel: VM? = null

    override fun getRootLayout(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        initDataBinding(inflater, container)
        return mBinding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initViewModel()
        initObserver()
        super.onViewCreated(view, savedInstanceState)
    }

    private fun initDataBinding(inflater: LayoutInflater, container: ViewGroup?) {
        if (layoutId != 0) {
            mBinding = DataBindingUtil.inflate(inflater, layoutId, container, false)
            mBinding!!.lifecycleOwner = this
        }
    }

    private fun initViewModel() {
        if (viewModel != null) {
            mModel = defaultViewModelProviderFactory.create(viewModel!!)
            if (variableId != 0) {
                mBinding?.setVariable(variableId, mModel)
            }
        }
    }

    protected open fun initObserver() {
        mModel?.loadingUI?.observe(viewLifecycleOwner, {
            if (it.display) {
                showLoading(it.msg)
            } else {
                dismissLoading()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding?.unbind()
        mBinding = null
        mModel = null
    }

    protected open val layoutId: Int = 0

    protected open val variableId: Int = 0

    protected open val viewModel: Class<VM>? = null

    abstract fun showLoading(msg: String? = null)

    abstract fun dismissLoading()

    abstract fun showToast(msg: String? = null)
}